package com.practice.util;

public class BinaryTreeNode {
	private BinaryTreeNode		parent;
	private BinaryTreeNode		left;
	private BinaryTreeNode		right;
	private int					value;
	
	public BinaryTreeNode(BinaryTreeNode parent, int n) {
		this.parent = parent;
		this.value 	= n;
	}
	
	public void addLeft(BinaryTreeNode left) {
		this.left = left;
	}
	
	public void addRight(BinaryTreeNode right) {
		this.right = right;
	}
	
	public BinaryTreeNode parent() {
		return this.parent;
	}
	
	public BinaryTreeNode left() {
		return this.left;
	}
	
	public BinaryTreeNode right() {
		return this.right;
	}
	
	public int value() {
		return this.value;
	}
	
	public BinaryTreeNode predecessor() {
		if (this.left != null) return treeMaximum(this.left);
		BinaryTreeNode node = this;
		BinaryTreeNode parent = this.parent;
		while (parent!=null && node==parent.left) {
			node = parent;
			parent = node.parent;
		}
		return parent;
	}
	
	public BinaryTreeNode successor() {
		if (this.right != null) return treeMinimum(this.right);
		BinaryTreeNode node = this;
		BinaryTreeNode parent = this.parent;
		while (parent!=null && node==parent.right) {
			node = parent;
			parent = node.parent;
		}
		return parent;
	}
	
	private BinaryTreeNode treeMaximum(BinaryTreeNode node) {
		while (node.right != null) node = node.right;
		return node;
	}
	
	private BinaryTreeNode treeMinimum(BinaryTreeNode node) {
		while (node.left != null) node = node.left;
		return node;
	}
}
